package com.tx.service;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tx.constant.WsEvent;
import com.tx.model.InMessage;
import com.tx.model.OutMessage;
import com.tx.model.WsSubMessage;
import com.tx.utils.WsResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * 
 * 功能描述：简单消息模板，用来推送消息
 专门发消息类的模板
 */
@Service
public class WebSocketService {


	@Autowired
	private SimpMessagingTemplate template;

	public void sendTopicMessage(String dest, InMessage message) throws InterruptedException {

		for (int i = 0; i < 2; i++) {
			Thread.sleep(500L);
			//template.convertAndSend(dest, new OutMessage(message.getContent() + i));

			Qumessage qz = new Qumessage();
			WsClient wsClient = new WsClient();

			System.out.println(message.getContent());

			String msg = message.getContent();
			if (JSONUtil.isJsonObj(msg)) {
				WsSubMessage wsMessage = JSON.parseObject(msg, WsSubMessage.class);
				WsEvent wsEvent = WsEvent.fromValue(wsMessage.getEvent());
				List<String> topics = wsMessage.getTopic();

				if (wsEvent == null || topics == null || topics.size() == 0) {
					return;
				}
				switch (wsEvent) {
					case SUB:
						// 订阅
						for (String topic : topics) {
							subTopic(wsClient, topic);
							qz.getobjkey(topic);
							template.convertAndSend(dest, new OutMessage(qz.message()));
							//	subTopic(wsClient, topic);
						}
						break;
					case UNSUB:
						// 退订
						for (String topic : topics) {
							//subTopic(wsClient, topic);
						}
						break;
					default:
						break;
				}


		/*	JSONObject obj = JSON.parseObject(message.getContent());
			if (obj.containsKey("topic")){
		//	String objkey  =obj.getString("topic");
			// 这个是错误的	JSONObject objkeyzong = JSON.parseObject(obj.getString("topic"));
				//System.out.println(objkeyzong.getJSONArray(1));
				JSONArray objkeyzong = obj.getJSONArray("topic");


				String objkey =null;

			   qz.getobjkey(objkey);


			//	JSONObject topicarray = JSON.parseObject(obj.getString("topic"));
				System.out.println(objkey );
			}
*/


			//	template.convertAndSend(dest, new OutMessage(qz.message()));
			}
		}
	}
	/**
	 * 订阅主题
	 * @param wsClient
	 * @param topic
	 */

	private void subTopic(WsClient wsClient, String topic) {
		// 判断主题


		wsClient.subTopic(topic);
		wsClient.send(WsEvent.SUBED.getValue(), topic, WsResultUtil.success("订阅成功！"));

		}



}
